/*
 ============================================================================
 Name        : fUtility.cpp
 Author      : zhuy
 Version     :
 Copyright   : Viva Copyright!
 Description : fUtility implementation
 ============================================================================
 */
#include <Aknappui.h>
#include <avkon.hrh>
#include <AknIndicatorContainer.h>
#include <aknenv.h>
#include <eikenv.h>
#include <eikapp.h>

#include <utf.h>
#include <bautils.h>
#include <sysutil.h>
//#ifndef __SERIES60_2X__
//#include <etelagsm.h>
//#include <etelbgsm.h>
//#else
//#include <etelmm.h>
//#include <EscapeUtils.h>
//#endif
#ifdef __SERIES60_3X__
#include "MyTelephony_3rd.h"
#else
#include <plpvariant.h>
#endif
//#include <e32cmn.h>
#include <Etel3rdParty.h>
#include <utf.h>
#include <eikenv.h>
#include <AknUtils.h>
#include <f32file.h>
#include "fUtility.h"
#include "ApplicationScheme.h"
#include <e32std.h>

//const TInt KFileSize = 600;

void fUtility::DeleteAFile( TFileName aFileName )
{
    ConeUtils iConeUtils;
    if( iConeUtils.FileExists( aFileName ) )
    {
        CCoeEnv::Static( )->FsSession( ).Delete( aFileName );
    }
}

TBool fUtility::FileExists( const TDesC& aPath )
{
    return ConeUtils::FileExists( aPath );
}
#if 0
void fUtility::WriteALineToAFile( const TDesC& aPathAndFileName, const TDesC &aDes )
{
    ConeUtils iConeUtils;
    RFs iFs;
    RFile iFile;
    TFileText iFileText;

    User::LeaveIfError( iFs.Connect( ) );
    if( iConeUtils.FileExists( aPathAndFileName ) )
    {
        User::LeaveIfError( iFile.Open( iFs, aPathAndFileName, EFileWrite ) );
    }
    else
    {
        iFs.MkDirAll( aPathAndFileName );
        User::LeaveIfError( iFile.Replace( iFs, aPathAndFileName, EFileWrite ) );
    }
    iFileText.Set( iFile );
    iFileText.Seek( ESeekEnd );
    User::LeaveIfError( iFileText.Write( aDes ) );

    iFile.Close( );
    iFs.Close( );
}
TBool fUtility::ReadALineFromAFile( const TDesC& aPathAndFileName, const TInt aLine, TDes &aDes )
{
    ConeUtils iConeUtils;
    RFs iFs;
    RFile iFile;
    TFileText iFileText;
    TInt i, anError;
    TBool forReturn;
    i = 0;
    anError = 0;
    if( iConeUtils.FileExists( aPathAndFileName ) )
    {
        User::LeaveIfError( iFs.Connect( ) );
        User::LeaveIfError( iFile.Open( iFs, aPathAndFileName, EFileRead ) );
        iFileText.Set( iFile );
        iFileText.Seek( ESeekStart );
        while( anError >= 0 )
        {
            YuebaoBuffer< 256 > temp;
            if( i == aLine )
            {
                anError = iFileText.Read( aDes );
                anError = -1;
                forReturn = ETrue;
            }
            else
            {
                if( iFileText.Read( temp ) == KErrEof )
                {
                    anError = -1;
                    forReturn = EFalse;
                }
            }
            i++;
        }
        iFile.Close( );
        iFs.Close( );
    }
    else
    forReturn = EFalse;
    return forReturn;

}
#endif
#if 0
TInt fUtility::Des2Int( const TDesC& aDes, TInt& aInt )
{
    TLex lex( aDes );
    return lex.Val( aInt );
}

TInt fUtility::Des2Int( const TDesC8& aDes, TInt& aInt )
{
    TLex8 lex( aDes );
    return lex.Val( aInt );
}

void fUtility::Int2Des( const TInt& aInt, TDes& aDes )
{
    aDes.Format( _L("%d"), aInt );
}

void fUtility::Int2Des( const TInt& aInt, TDes8& aDes )
{
    aDes.Format( _L8("%d"), aInt );
}
#endif

TInt fUtility::GetAppPath( TDes& aFileName )
{
    aFileName.Delete( 0, aFileName.Length( ) );
#if (!defined __WINSCW__ && !defined __WINS__)
#ifdef __SERIES60_3X__
    TFileName driver;
    TParse parse;
    parse.SetNoWild( CEikonEnv::Static( )->EikAppUi( )->Application( )->AppFullName( ), NULL, NULL );
    driver = parse.Drive( );
    TInt ret = CEikonEnv::Static( )->FsSession( ).PrivatePath( aFileName );
    aFileName.Insert( 0, driver );
    return ret;
#else
    return AknUtils::CompleteWithAppPath(aFileName);
#endif
#else
    aFileName.Append( KApplicationPath );
    return KErrNone;
#endif

}

// HBufC* fUtility::GetAppPath()
// {
// 	TFileName aFileName;
// 	aFileName.Delete(0,  aFileName.Length());
// 	TInt errorCode = KErrNone;
// #if (!defined __WINSCW__ && !defined __WINS__)
// #ifdef __SERIES60_3X__
// 	TFileName driver;
// 	TParse parse;
// 	parse.SetNoWild(CEikonEnv::Static()->EikAppUi()->Application()->AppFullName(), NULL, NULL);
// 	driver = parse.Drive();
// 	errorCode = CEikonEnv::Static()->FsSession().PrivatePath(aFileName);
// 	aFileName.Insert(0,driver);
// 	//return errorCode;
// #else
// 	errorCode = AknUtils::CompleteWithAppPath(aFileName);
// #endif
// #else
// 	aFileName.Append(_L("C:\\viva\\CCTV\\"));
// #endif
//
// 	if ( errorCode == KErrNone )
// 	{
// 		return aFileName.Alloc();
// 	}
// 	else
// 	{
// 		return NULL;
// 	}
// }

TBool fUtility::IsDigital( const TDesC& sDest )
{
    int length = sDest.Length( );
    if( length == 0 )
    {
        return EFalse;
    }
    for( int i = 0; i < length; i++ )
    {
        if( sDest[i] < 48 || sDest[i] > 57 )
        {
            return EFalse;
        }
    }
    return ETrue;
}

TBool fUtility::IsChinaMobileNumber( const TDesC& aPhoneNumber )
{
    TPtrC head( aPhoneNumber.Left( 3 ) );
    return ( aPhoneNumber.Length( ) == 11 && ( head.Compare( _L("134") ) == 0 || head.Compare( _L("135") ) == 0 || head.Compare( _L("136") ) == 0 || head.Compare( _L("137") ) == 0
            || head.Compare( _L("138") ) == 0 || head.Compare( _L("139") ) == 0 || head.Compare( _L("150") ) == 0 || head.Compare( _L("158") ) == 0 || head.Compare( _L("159") )
            == 0 ) && fUtility::IsDigital( aPhoneNumber ) );
}

#if 0
TInt fUtility::FileSize( const TDesC& aFileName )
{
    RFile file;
    TInt size;
    TInt re = file.Open( CEikonEnv::Static( )->FsSession( ), aFileName, EFileShareAny );////EFileShareReadersOnly
    if( re == KErrNone )
    re = file.Size( size );
    file.Close( );

    if( re == 0 )
    return size;
    else
    return re;
}

HBufC* fUtility::LoadFileTextL( const TDesC& aFileName )
{
    HBufC* bufH = NULL;
    RFile file;
    TInt size = 0;

    TInt re = 0;
    re = file.Open( CEikonEnv::Static( )->FsSession( ), aFileName, EFileShareReadersOnly | EFileStreamText );
    if( re == KErrNone )
    {
        re = file.Size( size );
    }

    if( size > 0 )
    {
        bufH = HBufC::NewL( KFileSize );
        if( bufH->Des( ).MaxLength( ) < size )
        bufH = bufH->ReAlloc( size );
        TPtr tmp( bufH->Des( ) );
        HBufC8* iBuf = HBufC8::NewLC( size );
        TPtr8 ptr( iBuf->Des( ) );
        file.Read( ptr );

        TInt returnValue = CnvUtfConverter::ConvertToUnicodeFromUtf8( tmp, ptr );
        CleanupStack::PopAndDestroy( );//iBuf
        User::LeaveIfError( returnValue );
    }
    file.Close( );
    return bufH;
}
#endif
#if 0
TBool fUtility::SaveToFile( const TDesC& aPathFile, const TDesC8& aSaveInfo )
{
    TInt ret;
    ret = CEikonEnv::Static( )->FsSession( ).MkDirAll( aPathFile );

    if( ( ret == KErrNone ) || ( ret == KErrAlreadyExists ) )
    {
        RFile file;
        ret = file.Create( CEikonEnv::Static( )->FsSession( ), aPathFile, EFileWrite );
        if( ret == KErrAlreadyExists )
        ret = file.Replace( CEikonEnv::Static( )->FsSession( ), aPathFile, EFileWrite );
        if( ret == KErrNone )
        {
            file.Write( aSaveInfo );
            file.Close( );
            return ETrue;
        }
        else
        return EFalse;
    }
    else
    return EFalse;
}

TBool fUtility::SaveToFile( const TDesC& aPath, const TDesC& aSaveInfo )
{
    HBufC8* hbuf = HBufC8::NewLC( aSaveInfo.Length( ) * 3 );
    TPtr8 buf( hbuf->Des( ) );
    TInt returnValue = CnvUtfConverter::ConvertFromUnicodeToUtf8( buf, aSaveInfo );
    if( returnValue == CnvUtfConverter::EErrorIllFormedInput || returnValue > 0 )
    {
        CleanupStack::PopAndDestroy( );
        return EFalse;
    }
    returnValue = SaveToFile( aPath, buf );
    CleanupStack::PopAndDestroy( );
    return returnValue;
}
#endif
#if 0
TBool fUtility::SearchFile( const TDesC& aPath, const TDesC& aSearchFile, TDes& aPathName )
{
    TFileName path;
    path.Copy( aPath );
    CDir* dir = NULL;
    if( CEikonEnv::Static( )->FsSession( ).GetDir( path, KEntryAttArchive | KEntryAttDir, ESortByDate | EDirsFirst | EDescending, dir ) != KErrNone )
    return EFalse;
    CleanupStack::PushL( dir );
    TInt ret( EFalse );
    TInt numberFiles = dir->Count( );
    for( TInt a = 0; a < numberFiles; a++ )
    {
        path.Delete( 0, path.Length( ) );
        path.Copy( aPath );
        const TEntry& file = ( *dir )[a];
        if( file.IsDir( ) )
        {
            path.Append( file.iName );
            path.Append( _L("\\") );
            ret = SearchFile( path, aSearchFile, aPathName );
            if( ret )
            break;
        }
        else
        {
            if( file.iName.Compare( aSearchFile ) == 0 )
            {
                aPathName.Copy( path );
                aPathName.Append( aSearchFile );
                ret = ETrue;
                break;
            }
        }
    }
    CleanupStack::PopAndDestroy( dir );
    return ret;
}
#endif
#if 0
void fUtility::GetUserAgentL( TDes& aAgent, TBool bActual, TBool /*bFull*/)
{
#if (defined __SERIES60_3X__)&&(!defined __WINS__)
#else
    if( bActual )
    {
#if (!defined __WINSCW__) && (!defined __WINS__)
#if (!defined __SERIES60_2X__) && (!defined __SERIES60_3X__)
        RTelServer iTelServer;
        RBasicGsmPhone iPhone;
        User::LeaveIfError(iTelServer.Connect());
        YuebaoBuffer<40> KTsyName;
        iTelServer.GetTsyName(0,KTsyName);
        // Load TSY
        TInt ret = iTelServer.LoadPhoneModule(KTsyName);
        if (ret != KErrNone)
        {
            iTelServer.Close();
            aAgent.Copy(_L("Nokia3650"));
            return;
        }

        // Get the phone name
        RTelServer::TPhoneInfo phoneInfo;
        ret = iTelServer.GetPhoneInfo(0, phoneInfo);
        if (ret != KErrNone)
        {
            iTelServer.UnloadPhoneModule(KTsyName);
            iTelServer.Close();
            aAgent.Copy(_L("Nokia3650"));
            return;
        }

        // Open the phone by name
        ret = iPhone.Open(iTelServer, phoneInfo.iName);
        if (ret != KErrNone)
        {
            iTelServer.UnloadPhoneModule(KTsyName);
            iTelServer.Close();
            aAgent.Copy(_L("Nokia3650"));
            return;
        }
        RBasicGsmPhone::TId id;
        ret = iPhone.GetGsmPhoneId(id);
        if (ret != KErrNone)
        {
            iPhone.Close();
            iTelServer.UnloadPhoneModule(KTsyName);
            iTelServer.Close();
            aAgent.Copy(_L("Nokia3650"));
            return;
        }
        if(id.iModelId.Find(_L("7650"))!=KErrNotFound)
        {
            aAgent = _L("Nokia7650");
            iPhone.Close();
            iTelServer.UnloadPhoneModule(KTsyName);
            iTelServer.Close();
            return;
        }
        iPhone.Close();
        iTelServer.UnloadPhoneModule(KTsyName);
        iTelServer.Close();
#endif
        HBufC8* userAgent = HBufC8::NewLC(160);
#if (defined __SERIES60_3X__)&&(!defined __WINS__)
#else
        userAgent = SysUtil::UserAgentStringL();
#endif
        if (bFull)
        {
            aAgent.Copy(userAgent->Des());
        }
        else
        {
            TInt pos = userAgent->Find(_L8("/"));
            if(pos!=KErrNotFound)
            aAgent.Copy(userAgent->Left(pos));
            else
            aAgent.Copy(userAgent->Des());
            CleanupStack::PopAndDestroy();
        }
#else
        aAgent.Copy( _L("S60 3rd 240x320 080323") );
#endif
    }
    else
    aAgent.Copy( _L("S60 3rd 240x320 080323") );
#endif
}
#endif
void fUtility::GetIMSINumberL( TDes& aData )
{
#ifdef __SERIES60_3X__
    CMyTelephony::GetIMSIL( aData );
#else
    TPlpVariantMachineId aId;
    PlpVariant::GetMachineIdL(aId);
    aData.Copy(aId);
#endif
}

void fUtility::GetIMEINumberL( TDes& aData )
{
#ifdef __SERIES60_3X__
    CMyTelephony::GetIMEIL( aData );
#else
    TPlpVariantMachineId aId;
    PlpVariant::GetMachineIdL(aId);
    aData.Copy(aId);
#endif
}

void fUtility::SendToBackground( )
{
    TApaTask task( CEikonEnv::Static( )->WsSession( ) );
    task.SetWgId( CEikonEnv::Static( )->RootWin( ).Identifier( ) );
    task.SendToBackground( );
}

#if 0
TBool fUtility::IsSounds( const TDesC& aFileExt, TBool aIsFullPath )
{
    _LIT( KESoundsExt, ".mp3.aac.mid." );

    HBufC* fullExt = MakfullExt( aFileExt, aIsFullPath );
    if ( fullExt == NULL )
    {
        return EFalse;
    }

    if ( KESoundsExt().Find( *fullExt ) == KErrNotFound )
    {
        delete fullExt;
        return EFalse;
    }
    else
    {
        delete fullExt;
        return ETrue;
    }
}

TBool fUtility::IsImages( const TDesC& aFileExt, TBool aIsFullPath )
{
    _LIT( KEImagesExt, ".jpg.gif.png." );

    HBufC* fullExt = MakfullExt( aFileExt, aIsFullPath );
    if ( fullExt == NULL )
    {
        return EFalse;
    }

    if ( KEImagesExt().Find( *fullExt ) == KErrNotFound )
    {
        delete fullExt;
        return EFalse;
    }
    else
    {
        delete fullExt;
        return ETrue;
    }
}

TBool fUtility::IsVideos( const TDesC& aFileExt, TBool aIsFullPath )
{
    _LIT( KEVideosExt, ".3gp.mp4.flv." );

    HBufC* fullExt = MakfullExt( aFileExt, aIsFullPath );
    if ( fullExt == NULL )
    {
        return EFalse;
    }

    if ( KEVideosExt().Find( *fullExt ) == KErrNotFound )
    {
        delete fullExt;
        return EFalse;
    }
    else
    {
        delete fullExt;
        return ETrue;
    }
}

TBool fUtility::IsTexts( const TDesC& aFileExt, TBool aIsFullPath )
{
    _LIT( KETextExt, ".txt.log.");

    HBufC* fullExt = MakfullExt( aFileExt, aIsFullPath );
    if ( fullExt == NULL )
    {
        return EFalse;
    }

    if ( KETextExt().Find( *fullExt ) == KErrNotFound )
    {
        delete fullExt;
        return EFalse;
    }
    else
    {
        delete fullExt;
        return ETrue;
    }
}

TBool fUtility::IsVivaEbook( const TDesC& aFileExt, TBool aIsFullPath )
{
    _LIT( KEVIVAExt, ".vad.vvm.");

    HBufC* fullExt = MakfullExt( aFileExt, aIsFullPath );
    if ( fullExt == NULL )
    {
        return EFalse;
    }

    if ( KEVIVAExt().Find( *fullExt ) == KErrNotFound )
    {
        delete fullExt;
        return EFalse;
    }
    else
    {
        delete fullExt;
        return ETrue;
    }
}

HBufC* fUtility::MakfullExt( const TDesC& aFileExt, TBool aIsFullPath )
{
    YuebaoBuffer<32> fileExt;
    if ( aIsFullPath )
    {
        int index = aFileExt.LocateReverse( TChar('.') );

        if( index != KErrNotFound )
        {
            TPtrC ext = aFileExt.Right( aFileExt.Length() - index );
            if ( ext.Length( ) > fileExt.MaxLength() )
            {
                return NULL;
            }
            fileExt.Copy( ext );
        }
        else
        {
            return NULL;
        }
    }
    else
    {
        if ( aFileExt.Length() > fileExt.MaxLength() )
        {
            return NULL;
        }
        fileExt.Copy( aFileExt );
    }

    YuebaoBuffer<32> fullExt;
    if ( fileExt[0] != '.' )
    {
        fullExt.Append( _L(".") );
    }
    fullExt.Append( fileExt );
    fullExt.Append( _L(".") );
    if ( fullExt.Length() <=2 )
    {
        return NULL;
    }
    return fullExt.Alloc();
}
#endif
const TUid KPhoneUidWmlBrowser =
    {
    0x10008D39
    };

void fUtility::LaunchWapBrowserL( const TDesC& aAddr )
{
    RApaLsSession iApaLsSession;
    TUid id( KPhoneUidWmlBrowser );
    TApaTaskList taskList( CEikonEnv::Static( )->WsSession( ) );
    TApaTask task = taskList.FindApp( id );

    if( task.Exists( ) )
    {
        HBufC8* param8 = HBufC8::NewLC( aAddr.Length( ) );
        param8->Des( ).Append( aAddr );
        task.SendMessage( TUid::Uid( 0 ), *param8 ); // UID is not used
        CleanupStack::PopAndDestroy( param8 );
    }
    else
    {
        if( !iApaLsSession.Handle( ) )
        {
            User::LeaveIfError( iApaLsSession.Connect( ) );
        }

        TThreadId thread;
        User::LeaveIfError( iApaLsSession.StartDocument( aAddr, KPhoneUidWmlBrowser, thread ) );
    }
    iApaLsSession.Close( );
}

TUint32 fUtility::Crc32( const TDesC& aDes )
{
    TUint32 crc = 0;
    if( aDes.Length( ) > 0 )
    {
        Mem::Crc32( crc, aDes.Ptr( ), aDes.Length( ) << 1 );
    }
    return crc;
}
TUint32 fUtility::Crc32( const TDesC8& aDes )
{
    TUint32 crc = 0;
    if( aDes.Length( ) > 0 )
    {
        Mem::Crc32( crc, aDes.Ptr( ), aDes.Length( ) );
    }
    return crc;
}
TUint32 fUtility::Crc32( void* data, int length )
{
    TUint32 crc = 0;
    if( length )
    {
        Mem::Crc32( crc, data, length );
    }
    return crc;
}
bool fUtility::IsValidEmail( const TDesC& aEmail )
{

    int dotIndex = -1;
    int atIndex = -1;

    int index = 0;
    TLex lex( aEmail );

    while( !lex.Eos( ) )
    {
        TChar ch = lex.Peek( );
        if( ch == '@' )
        {
            if( dotIndex == -1 )
            {
                dotIndex = index;
                if( dotIndex == 0 )
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else if( ch == '.' )
        {
            if( index == atIndex + 1 )
            {
                return false;
            }
            atIndex = index;
            if( atIndex == 0 )
            {
                return false;
            }
            if( dotIndex != -1 )
            {
                if( atIndex == dotIndex + 1 )
                {
                    return false;
                }
            }
            /*if( atIndex == -1 )
             {
             atIndex = lex.Offset( );
             if( dotIndex == -1 || dotIndex + 1 == atIndex )
             {
             return false;
             }
             }
             else
             {
             return false;
             }*/
        }
        else if( ( ch >= '0' && ch <= '9' )//
                || ( ch >= 'a' && ch <= 'z' )//
                || ( ch >= 'A' && ch <= 'Z' )//
                || ( ch == '-' ) //
                || ( ch == '-' ) //
        )
        {

        }
        else
        {
            return false;
        }
        index++;
        lex.Inc( );
    }

    if( atIndex == -1//
            || dotIndex == -1 //
            || atIndex < dotIndex //
            || atIndex >= aEmail.Length( ) - 1 - 1 )
    {
        return false;
    }

    return true;
}
//end of file
